const dbApi = require('../models/db')
const jwt = require('../utils/jwt')
const { uuid } = require('../config/config.default')
const handTime = require('../middleware/handtimestamp')
// 获取文章评论列表
exports.getCommentsList = async (req, res, next) => {
  let { type, source, page = 1 } = req.query
  if (!type) {
    res.status(400).json({
      message: 'Parameters of the so-called'
    })
    return
  }
  const onpage = page > 1 ? (page - 1) * 10 : 0
  let is_liking = false
  let token = req.headers.authorization
  token = token ? token.split('Bearer ')[1] : null
  try {
    if (type === 'a') {
      // 获取文章评论
      const sql = `SELECT a.id,a.commentText,a.article_id,a.time,a.username,a.replycount,a.praisecount,b.nickname,b.avatar FROM 
      usercomment a INNER JOIN users b ON a.username = b.username WHERE 
       a.article_id = ${source} ORDER BY a.time DESC LIMIT ${onpage},10`
      // 处理请求
      const data = await dbApi.query(sql)
      // 用户是否登录
      if (token) {
        // 存在则登陆
        const userInfo = await jwt.verify(token, uuid)
        // 当前登陆用户是否为评论点赞
        const clicksql = `SELECT * FROM commentpraise WHERE click_name ='${userInfo.uid}'`
        const clickdata = await dbApi.query(clicksql)
        data.forEach((item, index) => {
          is_liking = clickdata.some((value, index) => {
            return (
              value.comment_id === item.id &&
              value.click_name === userInfo.uid
            )
          })
          item.is_liking = is_liking
          item.type = type
        })
      } else {
        // 没有登陆
        data.forEach((item, index) => {
          item.is_liking = is_liking
          item.type = type
        })
      }

      page++
      res.status(201).json({
        data,
        page,
        message: 'successed'
      })
    } else if (type === 'c') {
      // 获取评论回复
      const sql = `SELECT a.id,a.comment_id,a.article_id,a.time,a.username,a.replytext as commentText ,a.praisecount,b.nickname,b.avatar FROM 
      userreply a INNER JOIN users b ON a.username = b.username WHERE
      a.comment_id = ${source} ORDER BY a.time DESC LIMIT ${onpage},10`
      // 处理请求
      const data = await dbApi.query(sql)
      if (token) {
        const userInfo = await jwt.verify(token, uuid)
        // //当前登陆用户是否为该回复点赞
        const clicksql = `SELECT * FROM replypraise WHERE  click_name  ='${userInfo.uid}'`
        const clickdata = await dbApi.query(clicksql)
        data.forEach((item, index) => {
          is_liking = clickdata.some((value, index) => {
            return (
              value.reply_id === item.id &&
              value.click_name === userInfo.uid
            )
          })
          item.is_liking = is_liking
          item.type = type
        })
      } else {
        // 没登录
        data.forEach((item, index) => {
          item.is_liking = is_liking
          item.type = type
        })
      }

      page++
      res.status(201).json({
        data,
        page,
        message: 'successed'
      })
    }
  } catch (error) {
    next(error)
  }
}

// 评论点赞
exports.addCommentsPraise = async (req, res, next) => {
  // 添加评论点赞记录
  const { commentId } = req.body
  try {
    const sql = `INSERT INTO commentpraise (comment_id,click_name)
    VALUES(${commentId},'${req.user.username}')`
    const { affectedRows: data } = await dbApi.query(sql)
    // 获取当前评论点赞总数
    const praisecountsql = `SELECT COUNT(*) as praisecount FROM commentpraise WHERE comment_id = ${commentId}`
    const praisecount = await dbApi.query(praisecountsql)
    // 将当前获取的总数更新至评论表总数记录
    const updatesql = `UPDATE usercomment SET praisecount = ${praisecount[0].praisecount}  WHERE id = ${commentId}`
    await dbApi.query(updatesql)
    data
      ? res.status(201).json({
        message: 'succeed'
      })
      : res.status(400).json({
        message: 'Invalid request'
      })
  } catch (error) {
    next(error)
  }
}

// 取消评论点赞
exports.delCommentsPraise = async (req, res, next) => {
  const { commentId } = req.body
  try {
    // 删除评论点赞记录
    const sql = `DELETE FROM commentpraise WHERE click_name ='${req.user.username}' AND comment_id = ${commentId}`
    const { affectedRows: data } = await dbApi.query(sql)
    // 获取当前评论点赞总数
    const praisecountsql = `SELECT COUNT(*) as praisecount FROM commentpraise WHERE comment_id = ${commentId}`
    const praisecount = await dbApi.query(praisecountsql)
    // 将当前获取的总数更新至评论表总数记录
    const updatesql = `UPDATE usercomment SET praisecount = ${praisecount[0].praisecount}  WHERE id = ${commentId}`
    await dbApi.query(updatesql)
    data
      ? res.status(201).json({
        message: 'succeed'
      })
      : res.status(400).json({
        message: 'Invalid request'
      })
  } catch (error) {
    next(error)
  }
}

// 发布评论或发布评论回复
exports.addComments = async (req, res, next) => {
  const { orId, content, art_id } = req.body
  console.log(orId, content, art_id)
  // 判断art_id是否传入，传入则为评论回复，否则为文章评论
  try {
    if (art_id) {
      // 评论回复
      // 添加回复
      const addsql = `INSERT INTO userreply (comment_id,article_id,replytext,username,praisecount)
                     VALUES (${orId},${art_id},'${content}','${req.user.username}',0)`
      const { affectedRows: data } = await dbApi.query(addsql)
      // 获取当前评论所有回复数
      const getCommentssql = `SELECT COUNT(*) as replycount FROM userreply WHERE comment_id = ${orId}`
      const comments = await dbApi.query(getCommentssql)
      // 更新文章评论数
      const updateCommentsql = `UPDATE usercomment SET replycount = ${comments[0].replycount}  WHERE id = ${orId}`
      await dbApi.query(updateCommentsql)
      // 获取当前发布的评论回复
      const commentsql = `SELECT a.id,a.comment_id,a.article_id,a.time,a.username,a.replytext as commentText,a.praisecount,b.nickname,b.avatar 
      FROM userreply a INNER JOIN users b ON a.username = b.username WHERE
      a.username ='${req.user.username}' AND a.replytext ='${content}' ORDER BY time DESC LIMIT 0,1	`
      const newdata = await dbApi.query(commentsql)
      data
        ? res.status(201).json({
          data: newdata[0],
          message: 'succeed'
        })
        : res.status(400).json({
          message: 'Invalid request'
        })
    } else {
      // 文章评论
      // 添加评论
      const addsql = `INSERT INTO usercomment (username,commentText,replycount,praisecount,article_id)
                     VALUES ('${req.user.username}','${content}',0,0,${orId})`
      const { affectedRows: data } = await dbApi.query(addsql)
      // 获取当前文章所有评论数
      const getCommentssql = `SELECT COUNT(*) as commentcount FROM usercomment WHERE article_id = ${orId}`
      const comments = await dbApi.query(getCommentssql)
      // 更新文章评论数
      const updateCommentsql = `UPDATE articles SET commentcount = ${comments[0].commentcount}  WHERE id = ${orId}`
      await dbApi.query(updateCommentsql)
      // 获取当前发布的评论
      const commentsql = `SELECT a.id,a.commentText,a.article_id,a.time,a.username,a.replycount,a.praisecount,b.nickname,b.avatar FROM 
      usercomment a INNER JOIN users b ON a.username = b.username WHERE 
      a.username ='${req.user.username}' AND a.commentText ='${content}' ORDER BY time DESC LIMIT 0,1	`
      const newdata = await dbApi.query(commentsql)
      data
        ? res.status(201).json({
          data: newdata[0],
          message: 'succeed'
        })
        : res.status(400).json({
          message: 'Invalid request'
        })
    }
  } catch (error) {
    next(error)
  }
}
